package com.wyix;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
    // 上传文件保存目录
    private static final String UPLOAD_DIR = "D:/upload_files/";

    public static void main(String[] args) {
        // 初始化上传目录
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            if (uploadDir.mkdirs()) {
                System.out.println("创建上传目录成功：" + UPLOAD_DIR);
            } else {
                System.err.println("创建上传目录失败：" + UPLOAD_DIR);
                return;
            }
        }

        try (ServerSocket serverSocket = new ServerSocket(9999)) {
            System.out.println("服务端启动，监听端口9999...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket socket) {
        try (DataInputStream in = new DataInputStream(socket.getInputStream());
             DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {

            // 读取操作类型（UPLOAD/DOWNLOAD）
            String operation = in.readUTF();

            if ("UPLOAD".equals(operation)) {
                // 处理文件上传
                String fileName = in.readUTF(); // 读取文件名
                long fileSize = in.readLong();  // 读取文件大小

                File saveFile = new File(UPLOAD_DIR + fileName);
                try (FileOutputStream fos = new FileOutputStream(saveFile)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    long received = 0;

                    // 接收文件内容
                    while (received < fileSize && (len = in.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        received += len;
                    }
                    out.writeUTF("上传成功：" + fileName + "（大小：" + received + "字节）");
                    out.flush();
                }

            } else if ("DOWNLOAD".equals(operation)) {
                // 处理文件下载
                String fileName = in.readUTF(); // 读取要下载的文件名
                File file = new File(UPLOAD_DIR + fileName);

                if (!file.exists() || !file.isFile()) {
                    out.writeUTF("文件不存在：" + fileName);
                    out.flush();
                    return;
                }

                // 发送文件存在标识、文件大小和文件内容
                out.writeUTF("FILE_EXISTS");
                out.writeLong(file.length());
                out.flush();

                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    out.flush(); // 确保最后一批数据发送
                }

            } else {
                out.writeUTF("无效操作类型：" + operation);
                out.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}